<template>
  <div>
    <FormPanel ref="from" :list="formList" @formChange="changeHandle" :isSubmitBtn="false" :collapse="false" labelWidth="110" />
    <BreakSpace label="经销商信息" />
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDrawer(1)">关 闭</el-button>
      <multiuse-button type="primary" :disabled="rowdata.isDisable" :click="closeDrawer.bind(this, 2)">保 存</multiuse-button>
    </div>
    <FilterTable
      ref="table"
      height="auto"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :columns="columns"
      :dataSource="tableList"
      :datakey="'records'"
      :uidkey="'dealerCode'"
      :onRowSelectChange="selectDlrChangeHandle"
      :onSyncTableData="syncDlrTableFun"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" :disabled="rowdata.isDisable" @click="addHandle(1)">导入经销商</multiuse-button>
        <multiuse-button size="small" type="primary" :disabled="rowdata.isDisable" @click="deleteHandle(1)">删 除</multiuse-button>
      </template>
    </FilterTable>
    <BreakSpace label="物料编码信息" />
    <FilterTable
      ref="table1"
      height="auto"
      :columns="columnsT"
      :fetchapi="fetchTApi"
      :params="fetchProjuctParams"
      :dataSource="tableListT"
      :datakey="'records'"
      :uidkey="'productCode'"
      :onRowSelectChange="selectProductChangeHandle"
      :onSyncTableData="syncProductTableFun"
      :onColumnsChange="columnsT => (this.columnsT = columnsT)"
    >
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" :disabled="rowdata.isDisable" @click="addHandle(2)">导入物料编码</multiuse-button>
        <multiuse-button size="small" type="primary" :disabled="rowdata.isDisable" @click="deleteHandle(2)">删 除</multiuse-button>
      </template>
    </FilterTable>
    <BaseDialog
      :visible.sync="importDlrVisible"
      :title="'导入经销商'"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
      @close="importDlrCloseHandler"
    >
      <importFiles :rowData="saveData" @close="importDlrCloseHandler" />
    </BaseDialog>
    <BaseDialog
      :visible.sync="importPorductVisible"
      :title="'导入物料编码'"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
      @close="importProductCloseHandler"
    >
      <importFilesT :rowData="saveData" @close="importProductCloseHandler" />
    </BaseDialog>
  </div>
</template>
<script>
import { addSave, getdealerList, getProductList, delDealerList, getListById, delProductList } from '@/api/omSale/vehicleParameters/PlanOrderTime/index.js';
import { dictionary } from '@/utils/dictMixin';
import importFiles from './importFiles';
import importFilesT from './importFilesT';
import moment from 'moment';
export default {
  data() {
    this.setId = -1;
    this.saveData = null;
    this.dlrTables = null;
    return {
      formList: this.createdFrom(),
      columns: this.createdTable(),
      columnsT: this.createdTableT(),
      formData: {},
      importDlrVisible: false,
      importPorductVisible: false,
      tableListT: [],
      tableList: [],
      fetchApi: getdealerList,
      fetchParams: { xhrAbort: true },
      fetchProjuctParams: { xhrAbort: true },
      fetchTApi: getProductList,
      selectedDlrRow: [], // 选中的行项目
      selectedProductRow: [] // 选中的行项目
    };
  },

  mixins: [dictionary],
  props: ['rowdata'],
  components: {
    importFiles,
    importFilesT
  },
  created() {
    console.log('this.setId=>' + this.setId);
  },
  methods: {
    createdFrom() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '设置信息'
        },
        {
          type: 'INPUT',
          label: '编号',
          fieldName: 'setNo',
          placeholder: '自动生成',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '设置类型',
          fieldName: 'setType',
          placeholder: '请选择',
          itemList: this.createDictList('2420'),
          initialValue: 24201001,
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '状态',
          fieldName: 'state',
          placeholder: '请选择',
          itemList: this.createDictList('1003'),
          initialValue: 10031001,
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          type: 'DATE',
          label: '年月',
          fieldName: 'yearMonth',
          placeholder: '请选择',
          dateType: 'month'
        },
        {
          type: 'RANGE_INPUT_NUMBER',
          label: '日期',
          fieldName: 'begAndendDate',
          placeholder: '请选择',
          initialValue: [],
          min: 1,
          max: 31,
          rules: [
            { required: true, message: '请输入1-31正整数...', trigger: 'blur' },
            {
              required: true,
              validator: (rule, value, callback) => {
                let Rep = /^[1-9]\d*$/;
                console.log('validator', value);
                if (!Rep.test(value[0])) {
                  return callback(new Error('请输入1-31正整数...'));
                }
                if (!Rep.test(value[1])) {
                  return callback(new Error('请输入1-31正整数...'));
                }
                if (parseInt(value[1]) < parseInt(value[0])) {
                  return callback(new Error('结束时间不能大于开始时间...'));
                }
                callback();
              },
              trigger: ['blur']
            }
          ]
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          align: 'center',
          width: 60,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '公司全称',
          dataIndex: 'dealerName',
          width: 400,
          align: 'center',
          sorter: true,
          filterType: 'input'
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filterType: 'input'
        },
        {
          title: '经销商简称',
          dataIndex: 'dealerShortname',
          sorter: true,
          filterType: 'input'
        },
        // {
        //   title: '经销商级别',
        //   dataIndex: 'shopLevel',
        //   sorter: true,
        //   filterType: 'input'
        // },

        {
          title: '省份',
          dataIndex: 'provinceName',
          sorter: true,
          filterType: 'input'
        },
        {
          title: '城市',
          dataIndex: 'cityName',
          sorter: true,
          filterType: 'input'
        },
        {
          title: '县区',
          dataIndex: 'districtName',
          sorter: true,
          filterType: 'input'
        }
      ];
    },
    // 删除
    async deleteHandle(type) {
      if (type == 1) {
        if (this.selectedDlrRow.length > 0) {
          this.$confirm('是否删除已勾选的经销商?', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(async () => {
              let res = await delDealerList(this.selectedDlrRow);
              if (res.resultCode == 200) {
                this.$notify({
                  title: '成功',
                  message: '删除成功',
                  type: 'success'
                });
              }
              //刷新当前界面
              this.fetchParams = { ...this.fetchParams };
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消'
              });
            });
        } else {
          this.$notify.warning({ title: '提示信息', message: '请您先选择数据' });
          return;
        }
      } else {
        if (this.selectedProductRow.length > 0) {
          this.$confirm('是否删除已勾选的物料?', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(async () => {
              let res = await delProductList(this.selectedProductRow);
              if (res.resultCode == 200) {
                this.$notify({
                  title: '成功',
                  message: '删除成功',
                  type: 'success'
                });
              }
              //刷新当前界面
              this.fetchProjuctParams = { ...this.fetchProjuctParams };
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消'
              });
            });
        } else {
          this.$notify.warning({ title: '提示信息', message: '请您先选择数据' });
          return;
        }
      }
    },

    createdTableT() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 60,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '物料编码',
          dataIndex: 'productCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '物料描述',
          dataIndex: 'productName',
          width: 400,
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车型名称',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配置名称',
          dataIndex: 'configName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '选装名称',
          dataIndex: 'optionName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '内饰',
          dataIndex: 'trimColorName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '外饰',
          dataIndex: 'colorName',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    addHandle(type) {
      if (this.setId == -1) {
        this.$notify({
          title: '警告',
          message: '请先保存设置信息',
          type: 'warning'
        });
        return;
      }
      if (type === 1) {
        this.importDlrVisible = true;
      } else {
        this.importPorductVisible = true;
      }
    },
    selectDlrChangeHandle(e) {
      this.selectedDlrRow = e.map(item => {
        return item.setDealerId;
      });
    },
    selectProductChangeHandle(e) {
      this.selectedProductRow = e.map(item => {
        return item.setProductId;
      });
    },
    changeHandle(val) {
      this.saveData = val;
      console.log('表单面板的数据：', val);
    },
    async closeDrawer(type) {
      if (type == 1) {
        this.$emit('close');
      } else {
        this.$refs.from.SUBMIT_FORM();
        if (this.saveData) {
          let params = Object.assign({}, this.saveData, { setId: this.setId });
          let json = JSON.parse(JSON.stringify(params));
          let res = await addSave(json);
          if (res.resultCode == 200) {
            this.saveData = res.data;
            this.setId = res.data['setId'];
            this.formList.forEach(x => {
              if (x.fieldName == 'begAndendDate') {
                const d = [];
                d.push(parseInt(res.data['begDay']), parseInt(res.data['endDay']));
                x.initialValue = d;
              } else {
                x.initialValue = res.data[x.fieldName];
              }
            });

            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success'
            });
            this.$emit('reflash');
          } else {
            this.saveData = null;
          }
        }
      }
    },
    // 关闭导入弹窗
    importDlrCloseHandler(val) {
      // console.log(val,this.saveData.setId)
      this.importDlrVisible = false;
      //刷新当前界面
      this.fetchParams = { ...this.fetchParams };
    },
    importProductCloseHandler(val) {
      this.importPorductVisible = false;
      // this.tableListT.concat(val);
      this.fetchProjuctParams = { ...this.fetchProjuctParams };
    },
    syncDlrTableFun(val) {
      // this.selectedDlrRow = val;
    },
    syncProductTableFun(val) {},
    async init(val) {
      let res = await getListById(val);
      if (res.resultCode == 200) {
        this.saveData = res.data;
        this.setId = res.data['setId'];
        this.formList.forEach(x => {
          if (x.fieldName == 'begAndendDate') {
            const d = [];
            d.push(parseInt(res.data['begDay']), parseInt(res.data['endDay']));
            x.initialValue = d;
          } else {
            x.initialValue = res.data[x.fieldName];
          }
        });
        this.fetchParams = { setId: this.setId };
        this.fetchProjuctParams = { setId: this.setId };
      }
    }
  },
  mounted() {
    if (this.rowdata.setId) {
      this.init(this.rowdata.setId);
    } else {
      this.setId = '-1';
    }
    this.dlrTables = this.$refs.table.$refs.pageTable;
  }
};
</script>
